import axios from "axios";
import qs from "qs";
import {Message} from "element-ui";
import router from "../routes.js";

const cachios = require('cachios');
const Axios = axios.create({
    baseURL: process.env.VUE_APP_API_HOST,
    timeout: 40000,
    responseType: "json",
    withCredentials: false, // 不需要cookie
});

const cachiosInstance = cachios.create(Axios, {
    stdTTL: 2,
    // checkperiod: 0,
});

//POST传参序列化(添加请求拦截器)
Axios.interceptors.request.use(
    config => {
        // 若是有做鉴权token , 就给头部带上token
        if (localStorage.getItem('token')) {
            config.headers.Authorization = 'Bearer ' + localStorage.getItem('token');
            config.headers.city = localStorage.getItem('cityId');
        }
        return config;
    },
    error => {
        Message({
            showClose: true,
            message: error,
            type: "error.data.error.message"
        });
        return Promise.reject(error.data.error.message);
    }
);
Axios.interceptors.response.use(
    res => {
        return res;
    },
    error => {
        if (error.message && (error.message.indexOf('timeout') > -1)) {
            Message({
                showClose: true,
                message: '网络请求超时',
                type: "error"
            });
            return Promise.reject(error);
        }
        if (error.response) {

            if (error.response.status === 401) {
                router.push({
                    path: "/login/index"
                });
            } else {
                Message({
                    showClose: true,
                    message: error.response.data.msg || '网络错误',
                    type: "error"
                });
            }
        }
        return Promise.reject(error);
    }
);
export default {
    install: function (Vue) {
        Object.defineProperty(Vue.prototype, "$http", {value: cachiosInstance});
    }
};
